# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: site-packages\PyInstaller\utils\osx.py
"""
Utils for Mac OS X platform.
"""
import os, sys
from ..compat import base_prefix, exec_command
from macholib.MachO import MachO


def is_homebrew_env():
    """
    Check if Python interpreter was installed via Homebrew command 'brew'.
    
    :return: True if Homebrew else otherwise.
    """
    env_prefix = get_homebrew_prefix()
    if env_prefix:
        if base_prefix.startswith(env_prefix):
            return True
        return False


def is_macports_env():
    """
    Check if Python interpreter was installed via Macports command 'port'.
    
    :return: True if Macports else otherwise.
    """
    env_prefix = get_macports_prefix()
    if env_prefix:
        if base_prefix.startswith(env_prefix):
            return True
        return False


def get_homebrew_prefix():
    """
    :return: Root path of the Homebrew environment.
    """
    prefix = exec_command(["/bin/bash", "-c", "which brew"]).strip()
    prefix = os.path.dirname(os.path.dirname(prefix))
    return prefix


def get_macports_prefix():
    """
    :return: Root path of the Macports environment.
    """
    prefix = exec_command(["/bin/bash", "-c", "which port"]).strip()
    prefix = os.path.dirname(os.path.dirname(prefix))
    return prefix


def fix_exe_for_code_signing(filename):
    """
    Fixes the Mach-O headers to make code signing possible.
    
    Code signing on OS X does not work out of the box with embedding
    .pkg archive into the executable.
    
    The fix is done this way:
    - Make the embedded .pkg archive part of the Mach-O 'String Table'.
      'String Table' is at end of the OS X exe file so just change the size
      of the table to cover the end of the file.
    - Fix the size of the __LINKEDIT segment.
    
    Mach-O format specification:
    
    http://developer.apple.com/documentation/Darwin/Reference/ManPages/man5/Mach-O.5.html
    """
    exe_data = MachO(filename)
    cmds = exe_data.headers[0].commands
    file_size = exe_data.headers[0].size
    for c in cmds:
        if c[0].get_cmd_name() == "LC_SYMTAB":
            data = c[1]
            new_strsize = file_size - data.stroff
            data.strsize = new_strsize

    linkedit = cmds[3][1]
    new_segsize = file_size - linkedit.fileoff
    linkedit.filesize = new_segsize
    linkedit.vmsize = new_segsize
    fp = open(exe_data.filename, "rb+")
    exe_data.write(fp)
    fp.close()
